<template>
    <div>
        <el-dialog v-bind="$attrs" :visible.sync="openHandles" v-on="$listeners" @open="onOpen" @close="onClose"
            title="新增素材" center :append-to-body="false">
            <el-row :gutter="24" style="padding-left: 50px;">
                <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="120px">
                    <el-col :span="11">
                        <el-form-item label="素材名称：" prop="materialTitle">
                            <el-input v-model="formData.materialTitle" placeholder="请输入素材名称" clearable
                                :style="{ width: '100%' }">
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="素材类型：" prop="type">
                            <el-select v-model="formData.type" placeholder="请选择素材类型" :style="{ width: '100%' }">
                                <el-option v-for="(item, index) in typeOptions" :key="index" :label="item.label"
                                    :value="item.value" :disabled="item.disabled"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="素材用途：" prop="materialIntroduction">
                            <el-input v-model="formData.materialIntroduction" placeholder="请输入素材用途" clearable
                                :style="{ width: '100%' }"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="素材状态：" prop="status">
                            <el-select v-model="formData.status" placeholder="请选择素材状态" :style="{ width: '100%' }">
                                <el-option v-for="(item, index) in shangjiaOptions" :key="index" :label="item.label"
                                    :value="item.value" :disabled="item.disabled"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="分 组：" prop="groupName">
                            <el-input v-model="formData.groupName" placeholder="请输入分 组" clearable
                                :style="{ width: '100%' }">
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="素材来源：" prop="sourceMaterials">
                            <el-select v-model="formData.sourceMaterials" placeholder="请输入素材来源"
                                :style="{ width: '100%' }">
                                <el-option v-for="(item, index) in sourceFrom" :key="index" :label="item.label"
                                    :value="item.value" :disabled="item.disabled"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="11">
                        <el-form-item label="上传：" prop="add_img" required>
                            <el-upload ref="add_img" :file-list="add_imgfileList" :action="add_imgAction"
                                :auto-upload="true" :data="{ 'folderType': formData.type }" :limit="1"
                                :before-remove="fileDel" :before-upload="add_imgBeforeUpload" :on-success="upSucc"
                                :on-error="onErr" :show-file-list="false" v-if="formData.type == 1">
                                <div v-if="add_imgfileList.length > 0" >
                                    <img :src="add_imgfileList[0].url" width="260" height="150">
                                    <div style="color:#165DFF ;" @click.stop="moveFile">删除</div>
                                </div>
                                <div class="box_add" v-if="!formData.add_img">
                                    <i class="el-icon-plus" style="font-size: 40px"></i>
                                </div>
                            </el-upload>

                            <el-upload ref="add_img" :file-list="add_imgfileList" :action="add_imgAction"
                                :auto-upload="true" :data="{ 'folderType': formData.type }" :limit="1"
                                :before-remove="delFile" :before-upload="add_imgBeforeUpload" :on-success="upSucc"
                                :on-error="onErr" v-if="formData.type !== 1">
                                <div class="box_add">
                                    <div v-if="formData.type == 3">
                                        <i class="el-icon-plus" style="font-size: 40;padding-top: 8px;"></i>
                                    </div>
                                    <div v-if="formData.type == 4">
                                        <i class="el-icon-video-play" style="font-size: 60px"></i>
                                    </div>
                                    <div v-if="![3, 4].includes(formData.type)">
                                        <i class="el-icon-plus" style="font-size: 40px;padding-top: 8px;"></i>
                                    </div>
                                </div>
                            </el-upload>
                        </el-form-item>
                    </el-col>

                    <el-col :span="11" v-if="formData.type == 2">
                        <el-form-item label="视频封面：" prop="add_imgs">
                            <el-upload ref="add_imgs" :file-list="add_videofileList" :action="add_videoImgAction"
                                :auto-upload="true" :data="{ 'folderType': 2 }" :limit="1" :before-remove="delFiles"
                                :on-success="upVideoSucc" :on-error="onErr" :show-file-list="false">
                                <div v-if="add_videofileList.length > 0"> <img :src="add_videofileList[0].url"
                                        width="260" height="150">
                                    <div style="color:#165DFF ;" @click.stop="moveVideoCover">删除</div>
                                </div>

                                <div>
                                    <div class="box_add" v-if="add_videofileList.length < 1" style="display: flex">
                                        <div><i class="el-icon-plus" style="font-size: 40px"></i></div>
                                    </div>
                                </div>
                            </el-upload>
                        </el-form-item>
                    </el-col>

                </el-form>
            </el-row>
            <div style="text-align: center;padding-top: 20px;">
                <el-button @click="close" style="width: 98px;">取消</el-button>
                <el-button type="primary" @click="handleConfirm">保存提交</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { postCommonFile, addMySources } from "@/api/my";
export default {
    inheritAttrs: false,
    components: {},
    props: ['isOnOpen'],
    data() {
        return {
            formData: {
                materialTitle: undefined,
                status: null,
                materialIntroduction: undefined,
                switch: false,
                groupName: undefined,
                sourceMaterials: undefined,
                add_img: null,
                add_imgs: null,  //上传验证用，视频封面
                type: null,  //素材类型
                sourceUrl: null,
                coverUrl: null,
            },
            kindOptions: [{
                "label": "授权下载",
                "value": 1
            }, {
                "label": "开放下载",
                "value": 2
            }],
            shangjiaOptions: [{
                "label": "上架",
                "value": 0
            }, {
                "label": "下架",
                "value": -1
            }],
            sourceFrom: [
                {
                    "label": "网络",
                    "value": 1
                }, {
                    "label": "委托",
                    "value": 2
                }, {
                    "label": "原创",
                    "value": 3
                },
            ],
            typeOptions: [{
                "label": "图片",
                "value": 1
            }, {
                "label": "视频",
                "value": 2
                // ,"disabled":true
            }, {
                "label": "音频",
                "value": 3
            }],
            rules: {
                status: [{
                    required: true,
                    message: '请选择素材状态',
                    trigger: 'change'
                }],

                materialTitle: [{
                    required: true,
                    message: '请输入素材名称',
                    trigger: 'blur'
                }],
                type: [{
                    required: true,
                    message: '请输入素材类型',
                    trigger: 'blur'
                }],
                materialIntroduction: [],
                groupName: [],
                sourceMaterials: [{
                    required: true,
                    message: '请输入素材来源',
                    // trigger: 'blur'
                }],
                add_img: [{
                    required: true,
                    message: '请选择上传视频',
                    trigger: 'change'
                }],
                add_imgs: [{
                    required: true,
                    message: '请选择上传视频封面',
                    trigger: 'change'
                }],
            },
            add_imgAction: process.env.VUE_APP_BASE_API + "/common/resourceFileUpload",
            add_videoImgAction: process.env.VUE_APP_BASE_API + "/common/commonFileUpload",
            add_imgfileList: [],
            add_videofileList: [],  //视频上传列表
        }
    },
    watch: {
        'formData.type'(ne, ol) {
            this.formData.add_img = false
            this.add_imgfileList = []
            this.add_videofileList = []
            // console.log(ne,'lll');
        },
    },
    computed: {
        openHandles: {
            get() {
                return this.isOnOpen
            },
            set() {
                this.fileDel()
                this.fileDels()
                this.formData.sourceUrl = null
                this.$emit('updateProp', false);
            }
        },
        imgEndUrl(url) {
            // return 123
            return (url) => {
                //  console.log(url,123);
                // const url = "https://ossapi.169000.net/zyykp/sourceMaterialImg/2024/01/22/hushi_20240122152939A001.jpeg";
                const filenameRegex = /.*\/([^/]*?)$/;
                const match = url.match(filenameRegex);
                if (match) {
                    return match[1]
                    console.log(match[1]);  // 输出: hushi_20240122152939A001.jpeg  
                } else {
                    console.log("没有找到文件名");
                    return url
                }
            }
        }
    },
    created() { },
    mounted() { },
    methods: {
        upVideoSucc(response, file, fileList) {  //视频封面上传成功
            //  console.log(response, file, 11111, response);
            if (response.code == 1000) {
                this.$notify.info({
                    message: '消息',
                    message: `${response.msg}`
                });

                this.add_videofileList = []
                return
            }
            this.add_videofileList.push({ url: response.data.url + response.data.filePath, name: this.imgEndUrl(response.data.filePath) })
            this.formData.add_imgs = response.data.filePath
            this.formData.coverUrl = response.data.filePath

        },
        upSucc(response, file, fileList) {  //文件上传成功  process.env.VUE_APP_ImgUrlHeader 
            // console.log(response);
            if (response.code == 1000) {
                this.$notify.info({
                    message: '消息',
                    message: `${response.msg}`
                });

                this.add_imgfileList = []
                return
            }
            this.add_imgfileList.push({ url: response.data.url + response.data.filePath, name: this.imgEndUrl(response.data.filePath) })
            this.formData.sourceUrl = response.data.filePath
            //  console.log(response, file, 22222, this.formData.sourceUrl);
        },
        onErr(e) { //文件上传失败
            //console.log(e,123);
            this.$notify.error({
                title: '提示',
                message: '上传文件错误，请稍后重试'
            });
        },
        onOpen() {

        },
        onClose() {
            this.formData.add_img = null           //校验
            this.formData.add_imgs = null
            this.add_imgfileList = []
            this.add_videofileList = []

            this.$refs['elForm'].resetFields()
        },
        updateProp(isOpen) {
            this.$emit('updateProp', isOpen);
        },
        fileDel() { //关闭前清空上传的校验和上传列表
            this.$refs['add_img'].uploadFiles = []  //关闭素材要清空上传列表
            this.formData.add_img = null
            this.add_imgfileList = []       //校验
        },
        fileDels() { //关闭前清空上传的校验和上传列表
            if (this.$refs['add_imgs']?.uploadFiles !== undefined) {
                this.$refs['add_imgs'].uploadFiles = []  //关闭素材要清空上传列表
                this.formData.add_imgs = null         //校验
            }

        },
        close() {
            // console.log(this.$refs['add_img'].uploadFiles.length > 0);  //判断是否上传图片
            this.fileDel()
            this.formData.sourceUrl = null
            this.updateProp(false)
            this.$emit('update:visible', false)
        },
        async addSour() {
            let res = await addMySources(this.formData)
            if (res.code == 200) {
                this.$notify.success({
                    message: '成功',
                    message: `${res.msg}`
                });
            } else {
                this.$notify.info({
                    message: '消息',
                    message: '操作失败，请稍后重试'
                });
            }

            // console.log(res);
        },
        checkFile() {
            if (this.$refs['add_img'].uploadFiles.length < 1) {
                this.formData.add_img = null
                return false
            } else {
                this.formData.add_img = true  //如果上传就赋值，下面会通过验证，然后再清空赋值
            }
            if (this.formData.type == 3) {
                // console.log(this.$refs['add_imgs']?.uploadFiles, 'ppp');
                if (this.$refs['add_imgs']?.uploadFiles?.length < 1) {
                    this.formData.add_imgs = null
                    return false
                } else {
                    this.formData.add_imgs = true  //如果上传就赋值，下面会通过验证，然后再清空赋值
                }
            }
            return true
        },
        handleConfirm() {
            // console.log(this.checkFile(),123);
            if (!this.checkFile()) {
                this.$notify.error({
                    title: '提示',
                    message: '请上传文件'
                });
                return
            }
            this.$refs['elForm'].validate(valid => {
                if (!valid) return
                //  if (!this.checkFile) return
                // console.log(this.checkFile());

                // return
                this.fileDel()
                // console.log(this.$refs['add_img'].uploadFiles.length > 0);
                // this.$refs['add_img'].submit()
                if (this.formData.sourceUrl == null) {
                    this.$notify.error({
                        title: '提示',
                        message: '请重新上传文件'
                    });
                    return
                }
                this.addSour()
                this.$emit('getList')
                this.close()
            })
        },
        add_imgBeforeUpload(file) {
            let isRightSize = file.size / 1024 / 1024 < 1000
            if (!isRightSize) {
                this.$message.error('文件大小超过 1000MB')
                return false
            }
           
            if (this.formData.type == undefined || this.formData.type == '') {
                this.$notify.info({
                    title: '消息',
                    message: '请选择素材类型'
                });
                return false
            }
            let PicisAccept = new RegExp('image/*').test(file.type)
            if (this.formData.type == 1) {
                if (!PicisAccept) {
                    this.$message.error('应该选择png，jpg，jpeg类型的文件')
                    return false
                }
            }
            let VideoisAccept = new RegExp('video/mp4').test(file.type)
            if (this.formData.type == 2) {
                if (!VideoisAccept) {
                    this.$message.error('应该选择MP4类型的文件')
                    return false
                }
            }

            let mP3isAccept = new RegExp('audio/mpeg').test(file.type)
            if (this.formData.type == 3) {
                if (!mP3isAccept) {
                    this.$message.error('应该选择MP3类型的文件')
                    return false
                }
            }

            this.formData.add_img = true
             return true 
           // return isRightSize
        },
        // fileDel() {

        // },
        delFile() {
            this.moveFile()
        },
        delFiles() {

        },
        moveVideoCover() {

            this.fileDels()
            this.add_videofileList = []
            // this.$message({
            //     type: 'success',
            //     message: '删除成功!'
            // });
            // this.$confirm('确定要删除视频封面', '提示', {
            //     confirmButtonText: '确定',
            //     cancelButtonText: '取消',
            //     type: 'warning'
            // }).then(() => {

            //     this.fileDels()
            //     this.add_videofileList = []
            //     this.$message({
            //         type: 'success',
            //         message: '删除成功!'
            //     });
            // }).catch(() => {

            // });
        },
        moveFile() {
            this.fileDel()
            this.add_imgfileList = []
            // this.$message({
            //     type: 'success',
            //     message: '删除成功!'
            // });

            // this.$confirm('确定要删除', '提示', {
            //     confirmButtonText: '确定',
            //     cancelButtonText: '取消',
            //     type: 'warning'
            // }).then(() => {

            // }).catch()
        },
    }
}

</script>

<style lang="scss">
.el-upload__tip {
    line-height: 1.2;
}

.box_add {
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
    width: 255px;
    height: 150px;
    border: 1px dashed #ccc;
    border-radius: 8px;
    // .img_box::hover{
    //     background-color: rgba(0, 0, 0, 0.8);
    // }
}

// .box_add:hover {
//     background-color: rgba(0, 0, 0, 0.8);
// }</style>

<style lang="scss" scoped>
::v-deep .el-upload-list__item {
    //width: 250px;
    //display: flex;
    // height: 100px;
}

::v-deep .el-upload-list {
    // margin-top: -10px;
}

::v-deep .el-upload-list__item {
    //height: 103px;
}
</style>